<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { useModulesStore } from '@/stores/modules'
import { getCurrentTheme, getTextColor, watchThemeChange, cleanupThemeWatch } from '@/utils/theme'

const modulesStore = useModulesStore()
const chartRef = ref(null)
const loading = ref(true)
let chartInstance = null
let themeWatchers = null

// 模拟依赖关系数据 - 使用图数据格式
const graphData = {
  nodes: [
    { name: 'Foundation', symbolSize: 60, category: 0 },
    { name: 'UIKit', symbolSize: 50, category: 1 },
    { name: 'CoreFoundation', symbolSize: 45, category: 2 },
    { name: 'libSystem', symbolSize: 40, category: 2 },
    { name: 'AppKit', symbolSize: 45, category: 1 },
    { name: 'CoreGraphics', symbolSize: 35, category: 2 },
    { name: 'Metal', symbolSize: 30, category: 2 },
    { name: 'AVFoundation', symbolSize: 35, category: 1 }
  ],
  links: [
    { source: 0, target: 1, value: 10 }, // Foundation → UIKit
    { source: 0, target: 2, value: 25 }, // Foundation → CoreFoundation
    { source: 0, target: 3, value: 15 }, // Foundation → libSystem
    { source: 2, target: 0, value: 8 },  // CoreFoundation → Foundation
    { source: 1, target: 0, value: 5 },  // UIKit → Foundation
    { source: 4, target: 0, value: 12 }, // AppKit → Foundation
    { source: 5, target: 0, value: 18 }, // CoreGraphics → Foundation
    { source: 6, target: 0, value: 7 },  // Metal → Foundation
    { source: 7, target: 1, value: 9 }   // AVFoundation → UIKit
  ],
  categories: [
    { name: '核心框架' },
    { name: 'UI框架' },
    { name: '系统框架' }
  ]
}

// 根据主题获取图表配置
const getChartOption = () => {
  const currentTheme = getCurrentTheme()
  const textColor = getTextColor(currentTheme)

  return {
    title: {
      text: '模块依赖关系',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: textColor
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: (params) => {
        if (params.dataType === 'node') {
          return `模块: ${params.name}<br/>类型: ${graphData.categories[params.data.category].name}`
        } else {
          const sourceNode = graphData.nodes[params.data.source].name
          const targetNode = graphData.nodes[params.data.target].name
          return `${sourceNode} → ${targetNode}<br/>依赖强度: ${params.data.value}`
        }
      },
      textStyle: {
        color: '#000000',
        fontWeight: 'bold'
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#333333',
      borderWidth: 1
    },
    legend: {
      data: graphData.categories.map(c => c.name),
      top: 'bottom',
      textStyle: {
        color: textColor,
        fontSize: 12,
        fontWeight: 'bold'
      }
    },
    series: [{
      type: 'graph',
      layout: 'force',
      data: graphData.nodes,
      links: graphData.links,
      categories: graphData.categories,
      roam: true,
      draggable: true,
      label: {
        show: true,
        position: 'bottom',
        distance: 5,
        fontSize: 12,
        color: '#000000',
        fontWeight: 'bold',
        borderColor: '#ffffff',
        borderWidth: 2,
        textShadowColor: '#ffffff',
        textShadowBlur: 4,
        textShadowOffsetX: 2,
        textShadowOffsetY: 2,
        backgroundColor: 'rgba(255, 255, 255, 0.8)',
        padding: [2, 4]
      },
      force: {
        repulsion: 1000,
        edgeLength: 150,
        gravity: 0.1
      },
      emphasis: {
        focus: 'adjacency',
        lineStyle: {
          width: 3
        }
      },
      lineStyle: {
        color: 'source',
        curveness: 0.3,
        width: 2
      },
      itemStyle: {
        borderColor: '#fff',
        borderWidth: 2
      }
    }]
  }
}

const initChart = () => {
  if (!chartRef.value) return

  // 检查容器尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    // 如果容器尺寸为0，等待下一帧再试
    requestAnimationFrame(() => {
      setTimeout(() => initChart(), 100)
    })
    return
  }

  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(getChartOption())

  // 设置主题变化监听
  themeWatchers = watchThemeChange(() => {
    if (chartInstance) {
      chartInstance.setOption(getChartOption())
    }
  })

  // 添加resize事件监听器，使用防抖
  let resizeTimer = null
  const resizeHandler = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = setTimeout(() => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }, 200)
  }

  window.addEventListener('resize', resizeHandler)

  // 保存清理函数
  chartInstance.cleanup = () => {
    window.removeEventListener('resize', resizeHandler)
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  }
}

onMounted(() => {
  setTimeout(() => {
    loading.value = false
    initChart()
  }, 500)
})

// 组件卸载时清理
onUnmounted(() => {
  if (themeWatchers) {
    cleanupThemeWatch(themeWatchers)
  }
  if (chartInstance) {
    if (chartInstance.cleanup) {
      chartInstance.cleanup()
    }
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;

  .chart {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
}
</style>